package zmee.pmas.form;

import kd.bos.context.RequestContext;
import kd.bos.entity.filter.ControlFilters;
import kd.bos.filter.FilterColumn;
import kd.bos.filter.FilterContainer;
import kd.bos.form.events.FilterContainerInitArgs;
import kd.bos.form.events.FilterContainerSearchClickArgs;
import kd.bos.form.field.events.BeforeFilterF7SelectEvent;
import kd.bos.form.field.events.BeforeFilterF7SelectListener;
import kd.bos.list.IListView;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;

import java.util.EventObject;
import java.util.List;

/**
 * @Author: xw
 * @Date: 2023/02/22/14:30
 * @Description: 联系单列表【组织】设置默认当前登录组织
 */
public class ContactListPlugin extends AbstractListPlugin implements BeforeFilterF7SelectListener {

    /**
     * 用户是否点击了过滤面板搜索按钮
     */
    private boolean isClickSearched = false;

    /**
     * 筛选组织
     */
    private long orgId = 0;

    @Override
    public void filterContainerInit(FilterContainerInitArgs args) {
        super.filterContainerInit(args);
        List<FilterColumn> commonFilterColumns = args.getCommonFilterColumns();
        for (FilterColumn filterColumn : commonFilterColumns) {
            if ("zmee_orgfield.name".equals(filterColumn.getFieldName())) {
                if (!isClickSearched) {
                    orgId = RequestContext.get().getOrgId();
                }
                filterColumn.setDefaultValue(String.valueOf(orgId));
            }
        }
    }

    @Override
    public void filterContainerSearchClick(FilterContainerSearchClickArgs args) {
        isClickSearched = true;
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        FilterContainer filterContainer = this.getView().getControl(FILTERCONTAINERID);
        filterContainer.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeFilterF7SelectEvent args) {
        String fieldName = args.getFieldName();
        if ("projectname.id".equals(fieldName)) {
            ControlFilters filters = ((IListView) this.getView()).getControlFilters();
            List<Object> org = filters.getFilter("zmee_orgfield.id");
            if (org.isEmpty()) {
                return;
            }
            List<QFilter> qfilters = args.getQfilters();
            QFilter filter = new QFilter("useorg", QCP.in, org);
            qfilters.add(filter);
            args.setQfilters(qfilters);
        }
    }
}
